package cn.edu.nju.software;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;

public class SwapToTarget {
	private String[] standardN = new String[]{"SIDS",
			"SID",
			"STUDNETCOURSES",
			"STUDNETCOURSE",
			"INSTITUTE",
			"COURSES",
			"COURSE",
			"CIDS",
			"CID",
			"NAME",
			"TEACHER",
			"TIME",
			"PALCE",
			"SHARABLE",
			"GRADE"};
	
	private String fromServer;
	private String standardPath;
	private String[] targetPath = new String[2];
	private String[] targetServer = new String[2];
	
	public SwapToTarget(String fromServer, String standard) {
		this.fromServer = fromServer;
		this.standardPath = standard;
		targetPath[0] = standardPath.substring(0, 4) + "3(1)" + standardPath.substring(5);
		targetPath[1] = standardPath.substring(0, 4) + "3(2)" + standardPath.substring(5);
		initTargetServer();
		swap();
	}

	private void initTargetServer() {
		// TODO Auto-generated method stub
		if(fromServer == "A") {
			targetServer[0] = "B";
			targetServer[1] = "C";
		}
		else if(fromServer == "B") {
			targetServer[0] = "A";
			targetServer[1] = "C";
		}
		else if(fromServer == "C") {
			targetServer[0] = "A";
			targetServer[1] = "B";
		}
	}

	private void swap() {
		// TODO Auto-generated method stub
		File file = new File(standardPath);
		File targetFile;
	    for (int j = 0; j < 2; j++) {
	    	try {
				targetFile = new File(targetPath[j]);
				Scanner input  = new Scanner(file);
				PrintWriter output = new PrintWriter(targetFile);
				String s = "";
				
				while(input.hasNext()) {
					s += input.nextLine();
				}
				for(int i = 0; i < standardN.length; i++) {
					s = s.replaceAll(standardN[i], targetServer[j] + standardN[i]); 
				}
				
				output.write(s);
				
				input.close();
				output.close();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	    }
		
	}
	
	public String[] getTargetPath() {
		return targetPath;
	}
	
	public String[] getTargetServer() {
		return targetServer;
	}
}
